<?php

namespace App\Controller\LazyCommon;

use App\Base\BaseConfig;
use App\Base\BaseController;
use App\Model\LazyCommon\UserModel;
use App\Model\LazyCommon\UserInviteModel;
use App\Model\LazyCommon\MiniAppModel;
use App\Model\LazyCommon\WechatModel;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

/**
 * @route("/wechat")
 */
class WechatLoginController extends BaseController
{
    /**
     * @Route("/ajaxLogin",name="WechatAjaxLogin")
     */
    public function WechatAjaxLogin()
    {
        $WechatModel = new WechatModel($this->getDoctrine());
        if(!$code = $this->getParamRequired("code")){
            //没有CODE就获取一下
            $WechatModel->getWeChatCode(BaseConfig::__BASE_API__."/wechat/ajaxLogin",1);die;
        }
        try {
            $WechatModel->getAccessToken4UserInfo($code);
            $userInfo = $WechatModel->getWeChatUserInfo();
        } catch (\Exception $e) {
            return $this->json_out(0,"登录失败");
        }
        $UserModel = new UserModel($this->getDoctrine());

        $user = $UserModel->getByWeChetId($userInfo->openid);
        $user->setHeadPic($userInfo->headimgurl)
            ->setNickName($userInfo->nickname);

        $this->myEm()->persist($user);
        $this->myEm()->flush();
        $userSessionData = $UserModel->createSessionData($user);
        $this->mySession()->set("user",$userSessionData);
        return $this->json_out(1,"登陆成功");
    }
}
